<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Model\StudentsModel;
use App\Http\Controllers\PublicController;
use Illuminate\Support\Facades\DB;

class StudentController extends Controller
{
    //登录
    public function login_POST(Request $requst)
    {
        //用户名
        $username = $requst->request->get('username');
        //密码
        $pwd = $requst->request->get('password');


        //判断非空
        if (!($pwd && $username)) {
            die(\json_encode(['error'=>'用户名或者密码不能为空']));
        }

        //返回值
        $return = null;
        $db_res = StudentsModel::where([
            ['stu_id',$username],
            ['password',$pwd],
        ])->first();
        if ($db_res) {
            if ($db_res->password == 'stu'.$username) {
                //判断是否为初次密码
                $return = ['warning'=>'初次登陆，需要重设密码后，方能填报志愿'];
            } else {
                $return = [
                    'token'=>PublicController::getJwt('stu', $username),
                    'data'=>[
                        'stu_id'=>$username,
                        'name'=>$db_res->name,
                    ]
                ];
            }
        } else {
            $return = [
                'error'=>'用户名或者密码错误'
            ];
        }
        return json_encode($return);
    }

    //志愿填报修改
    public function wish_POST(Request $requst)
    {
        $nowtime = time();//当前时间
        $timeconfig=DB::table('timeconfig')->first();//从数据库中获取填报时间
        $timeconfig=  json_decode(json_encode($timeconfig),true);
        if($nowtime > $timeconfig['endtime']){
            die(json_encode(['warning'=>'志愿填报已经结束']));
        }

        if($nowtime <= $timeconfig['starttime']){
            die(json_encode(['warning'=>'还未开始填报志愿呦']));
        }
        //志愿信息
        $wish = $requst->request->get('wish');

        //学号
        $stu_id = $requst->request->get('stu_id');

        //判断token和传入的stu_id是否相同
        if ($stu_id != $requst->login_username) {
            die(json_encode(['error'=>'偷来的token？']));
        }

        //在这里进行专业验证，先加一个简单的去重
        if ($wish!=array_unique($wish)) {
            die(json_encode(['error'=>'专业重复']));
        }

        //读取最大填写次数
        $maxTimes = \config('my.upload')['wished_times'];

        //#在此处判断接受到的字段是否合法

        //返回值
        $returnVal = null;

        //开启回滚
        DB::beginTransaction();
        try {
            //#在此处判断接受到的字段是否合法
            $res_db = StudentsModel::where('stu_id', $stu_id)->first();
            if (!$res_db) {
                die(json_encode(['error'=>'学号不存在['.$stu_id.']']));
            } else {
                if (!($res_db->wished_times < $maxTimes)) {
                    die(json_encode(['error'=>'您已经填报了'.$maxTimes.'次了，不能再修改了']));
                }
                $wish['wished_times']=++$res_db->wished_times;

                $res_db->update($wish);
                $res_db->save();
            }
            $returnVal = json_encode(['message'=>'修改成功']);
            //提交
            DB::commit();
        } catch (\Illuminate\Database\QueryException $e) {//捕捉异常
            $returnVal = json_encode(['error'=>'修改失败']);
            //回滚
            DB::rollBack();
        }
        return $returnVal;
    }

    //获取自身信息
    public function self_GET(Request $requst)
    {


        //当前方向数量
        $subjectLen=DB::table('direction')->select('dir_name')->count();


        //id通过token解析获得
        $stu_id = $requst->login_username;


        //返回值
        $returnVal = null;
        //开启回滚
        DB::beginTransaction();
        try {
            //#在此处判断接受到的字段是否合法
            $res_db = StudentsModel::where('stu_id', $stu_id)->first();
            if (!$res_db) {
                die(json_encode(['error'=>'学号不存在['.$stu_id.']']));
            } else {
                $oldData=json_decode($res_db,true);
                $wishData=[];
                for ($i=0;$i<$subjectLen;$i++){
                    $wishData['wish'.strval($i+1)]=$oldData['wish'.strval($i+1)];
                }
                $returnVal = [
                    'wished_times'=>$res_db->wished_times,
                    'wish'=>(!$res_db->wish1)?null:$wishData
                ];
            }
            //提交
            DB::commit();
        } catch (\Illuminate\Database\QueryException $e) {//捕捉异常
            $returnVal = ['error'=>'非法操作'];
            //回滚
            DB::rollBack();
        }
        return json_encode($returnVal);
    }

    //修改学生密码
    public function pwd_POST(Request $requst)
    {
        //用户名
        $username = $requst->request->get('username');
        //密码
        $pwd = $requst->request->get('password');

        //新密码
        $newpwd = str_replace(' ', '', $requst->request->get('newpassword'));

        //简单的验证，判断长度
        if (strlen($newpwd)>18) {
            die(json_encode(['error'=>'密码长度最多不超过18位']));
        }

        //判断是否与原密码相同
        if ($pwd == $newpwd) {
            die(json_encode(['error'=>'新密码不能与原密码相同']));
        }

        //判断非空
        if (!($pwd && $username && $newpwd)) {
            die(\json_encode(['error'=>'用户名或者密码/新密码不能为空']));
        }

        //返回值
        $return = null;
        $db_res = StudentsModel::where([
            ['stu_id',$username],
            ['password',$pwd],
        ])->first();
        if ($db_res) {
            $db_res->password = $newpwd;
            $db_res->save();
            //开启回滚
            DB::beginTransaction();
            try {
                //修改密码
                $db_res->password = $newpwd;
                $db_res->save();
                //提交
                DB::commit();
            } catch (\Illuminate\Database\QueryException $e) {//捕捉异常
                $returnVal = ['error'=>'数据库错误请联系管理员'];
                //回滚
                DB::rollBack();
            }

            //登录
            $requst->request->set('username',$username);
            $requst->request->set('password',$newpwd);

            //获取token
            $return = json_decode(self::login_POST($requst));
        } else {
            $return = [
                'error'=>'用户名或者密码错误'
            ];
        }

        return json_encode($return);
    }
}
